package net.lucamasini.ricette.client.ingredienti;

import static net.lucamasini.ricette.client.ServiceBus.getEventbus;

import java.util.List;

import net.lucamasini.ricette.client.RicettarioRequestFactory;
import net.lucamasini.ricette.client.ServiceBus;
import net.lucamasini.ricette.client.ingredienti.event.NewListaIngredientiEvent;
import net.lucamasini.ricette.client.ingredienti.event.RefreshListaIngredientiEvent;

import com.google.gwt.core.client.GWT;
import com.google.gwt.requestfactory.shared.Receiver;

public class IngredientiServiceBroker implements RefreshListaIngredientiEvent.Handler {

	private final static RicettarioRequestFactory requestFactory = GWT.create(RicettarioRequestFactory.class);
	
	private List<IngredienteProxy> cachedResult;
	
	@Override
	public void onRefreshListaIngredientiRequest(RefreshListaIngredientiEvent event) {
		
		requestFactory.initialize(ServiceBus.getEventbus());
		
		if(cachedResult==null || event.isClearCache()) {
			requestFactory.ingredientiRequest().findAllIngredienti().fire(new Receiver<List<IngredienteProxy>>() {
				public void onSuccess(List<IngredienteProxy> result) {
					cachedResult = result;
					getEventbus().fireEvent(new NewListaIngredientiEvent(result));
				}
			});
		} else {
			getEventbus().fireEvent(new NewListaIngredientiEvent(cachedResult));
		}
		
		
	}
}
